﻿using System.IO;
using System.Xml;
using System.Net;

namespace ServBus.ListForm2010.Utility
{
    public class Utility
    {
        public static void WriteContentToFile(string filePath, string content)
        {
            using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                StreamWriter sw = new StreamWriter(fs);
                sw.Write(content);
                sw.Flush();
            }
        }

        public static void SaveDoc(XmlDocument doc, string path)
        {

            doc.Save(path);
        }

        public static string GetInternalName(string p_fieldName)
        {
            if (p_fieldName.StartsWith("my:"))
            {
                p_fieldName = p_fieldName.Substring("my:".Length);
            }

            return p_fieldName;
        }

        /// <summary>
        /// 获取配置文件信息
        /// </summary>
        /// <param name="p_field_name">配置字段名称</param>
        /// <returns></returns>
        public static string GetXmlValue(string p_node_name, string p_site_url)
        {
            string result = "";
            XmlUrlResolver m_resolver = new XmlUrlResolver();
            m_resolver.Credentials = CredentialCache.DefaultCredentials;
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.XmlResolver = m_resolver;
            xmlDoc.Load(p_site_url + "/_layouts/InfoPathServe/Setting/InfoPathServeSetting.xml");
            XmlNode root = xmlDoc.DocumentElement;
            XmlNode xmlNode = root.SelectSingleNode(p_node_name);
            result = xmlNode.Attributes["Value"].Value;
            return result;
        }

        //TO DO 考虑并发
        public static string SchemaFile = "lookup";
        public static int FileCount = 1;
        public static string GetLookupSchemaFileName()
        {
            string extension = FileCount.ToString();

            FileCount++;

            return SchemaFile + extension;
        }

        /// <summary>
        /// 文件编码转换
        /// </summary>
        /// <param name="sourceFile">源文件</param>
        /// <param name="destFile">目标文件，如果为空，则覆盖源文件</param>
        /// <param name="targetEncoding">目标编码</param>
        public static void ConvertFileEncoding(string sourceFile, string destFile, System.Text.Encoding targetEncoding)
        {
            destFile = string.IsNullOrEmpty(destFile) ? sourceFile : destFile;
            System.IO.File.WriteAllText(destFile,
                                        System.IO.File.ReadAllText(sourceFile, System.Text.Encoding.UTF8),
                                        targetEncoding);
        }

    }
}